package cn.edu.abtu.service.impl;

import cn.edu.abtu.config.oss.OssProperties;
import cn.edu.abtu.service.FileService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    private OssProperties ossProperties;

    @Override
    public String upload(MultipartFile file) {
        //获取AccessKeyId
        String keyId = ossProperties.getKeyId();
        //获取AccessKeySecret
        String keySecret = ossProperties.getKeySecret();
        //获取地域节点
        String endPoint = ossProperties.getEndPoint();
        //获取BucketName
        String bucketName = ossProperties.getBucketName();
        try {
            OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + fileName;
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean deleteFile(String url) {
        //获取AccessKeyId
        String keyId = ossProperties.getKeyId();
        //获取AccessKeySecret
        String keySecret = ossProperties.getKeySecret();
        //获取地域节点
        String endPoint = ossProperties.getEndPoint();
        //获取BucketName
        String bucketName = ossProperties.getBucketName();
        try {
            OSS ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);
            String host = "https://" + bucketName + "." + endPoint + "/";
            String fileName = url.substring(host.length());
            ossClient.deleteObject(bucketName,fileName);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
